<?php

/**
 * 
 * Class for setting and removing user session
 * @author sbojchuk
 * @todo create working with cookies
 *
 */

class Auth {
	
	private static $userObj;
	
	
	/**
	 * @return user object - if user is authorized
	 * @return false - if user isn't authorized
	 */
	public static function getInstanse() {
		
		if (isset ( $_SESSION ['user_id'] )) {
			if (! self::$userObj) {
				
				$db = Db::getInstance();
				//get all fields except password
				$stmt = $db->prepare ( "SELECT * FROM users WHERE id =  ? LIMIT 1" );
				$stmt->execute ( array ($_SESSION ['user_id'] ) );
				
				self::$userObj = $stmt->fetch ();
			}
			
			return self::$userObj;
		
		} else {
			return false;
		}
	}
	
	/**
	 * @return true - if user pass authorization
	 * @return false - if user can't pass authorization
	 */
	public static function authorize($login, $password) {
		$db = Db::getInstance();
		$stmt = $db->prepare ( "SELECT id FROM users WHERE login = ? and password = md5(?) LIMIT 1" );
		$stmt->execute ( array ($login, $password ) );
		
		$res = $stmt->fetchColumn ();
		//check if user exists and his id to session
		if ($stmt->rowCount () == 1) {
			$user_id = $res ['id'];
			$_SESSION ['user_id'] = $user_id;
			return true;
		} else {
			return false;
		}
	}
	
	public static function getAuthUserId() {
		if (isset ( $_SESSION ['user_id'] )) {
			echo "<p>". $_SESSION ['user_id']."</p>";
			return $_SESSION ['user_id'];
		}
		return null;
	}
	
	public static function logout(){
		session_destroy();
		session_unset();
		unset($_SESSION['user_id']);
	}

}

?>